<?php

namespace App\Cache;

//use Redis;
use Redis;
use Log;
use App\Models\Attention;
use App\Models\Followers;
use App\Models\Favorite;
use App\Models\Praise;

class MRedisLib {

    /**
     * 存REDIS缓存
     * @param int  $userId     用户id
     * @param int  $contentId  内容id
     * @return bool
     */
    private $preKey = 'CBN4API';
    private $redis;
    
    public function __construct(){
        GLOBAL $gRedis;
        $this->preKey = env('REDIS_CACHE_PREFIX');
        $this->redis = $gRedis;
//        $this->redis = new Redis();
//        $this->redis->connect(env('REDIS_HOST'), env('REDIS_PORT'));
//        $this->redis->auth(env('REDIS_PWD'));
    }

    public function setHandle($action, $pre, $par1, $par2, $par3 = '') {
        $sstr_pre = $pre;
        $sstr = substr($pre, 1,1);
        $pre = $this->preKey.$pre;
        foreach ($par1 as $key1 => $value1) {
            break;
        }
        foreach ($par2 as $key2 => $value2) {
            break;
        }
        $str_v1 = $value2;
        $str_v2 = $value1;
        if ($par3) {
            $str_v1 = $value2 . '_' . $par3;
            $str_v2 = $value1 . '_' . $par3;
        }
        if(!$value1 || !$value2){
            return FALSE;
        }
        $ret = false;
        if ('add' == $action) {
//            Log::info("评论:".$pre . '_' . $key1 . '_' . $value1);
//            Log::info("评论1111:".$pre . '_' . $key2 . '_' . $value2);
            $ret = $this->redis->multi()
                    ->zAdd($pre . '_' . $key1 . '_' . $value1, time(), $str_v1)
                    ->zAdd($pre . '_' . $key2 . '_' . $value2, time(), $str_v2)
                    ->exec();
            //PFA 点赞收藏关注
            if($sstr == 'P'|| $sstr == 'F' || $sstr == 'A' ){
                //查找集合中是否有该元素
                $socre = $this->redis->zScore($this->preKey.'_PFA',$sstr_pre . '_' . $value1 . '_' . $value2);
                if($socre && !($socre%10)){
                    //删除
                    $this->redis->zDelete($this->preKey.'PFA',$sstr_pre . '_' . $value1 . '_' . $value2);
                } else {
                    $this->redis->zAdd($this->preKey.'PFA',time()*10+1,$sstr_pre . '_' . $value1 . '_' . $value2);
                }
            }
        } else if ('delete' == $action) {
            $ret = $this->redis->multi()
                    ->zDelete($pre . '_' . $key1 . '_' . $value1, $str_v1)
                    ->zDelete($pre . '_' . $key2 . '_' . $value2, $str_v2)
                    ->exec();
            //PFA 点赞收藏关注
            if($sstr == 'P'|| $sstr == 'F' || $sstr == 'A' ){
                //查找集合中是否有该元素
                $socre = $this->redis->zScore($this->preKey.'PFA',$sstr_pre . '_' . $value1 . '_' . $value2);
                if( $socre && ($socre%10)){
                    //删除
                    $this->redis->zDelete($this->preKey.'PFA',$sstr_pre . '_' . $value1 . '_' . $value2);
                } else {
                    $this->redis->zAdd($this->preKey.'PFA',time()*10,$sstr_pre . '_' . $value1 . '_' . $value2);
                }
            }
        } else if ('deleteAll' == $action) {
            $data = $this->redis->zRange($pre . '_' . $key1 . '_' . $value1, 0, -1, true);
            $this->redis = $this->redis->multi();
            $ret = FALSE;
            if ($par3) {
                if($data){
                    foreach ($data as $key => $value) {
                        $str = explode('_', $key);
                        if (isset($str[0]) && isset($str[1])) {
                            $str_v1 = $str[0] . '_' . $str[1];
                            $str_v2 = $value1 . '_' . $str[1];
                            $this->redis = $this->redis->zDelete($pre . '_' . $key1 . '_' . $value1, $str_v1)
                                        ->zDelete($pre . '_' . $key2 . '_' . $str[0], $str_v2);
                        }
                    }
                    $ret = $this->redis->exec();
                }
            } else {
                if($data){
                    foreach ($data as $key => $value) {
                        $this->redis = $this->redis->zDelete($pre . '_' . $key1 . '_' . $value1, $key)
                                    ->zDelete($pre . '_' . $key2 . '_' . $key, $value1);
                        //PFA 点赞收藏关注
                        if($sstr == 'P'|| $sstr == 'F' || $sstr == 'A' ){
                            //查找集合中是否有该元素
                            $socre = $this->redis->zScore($this->preKey.'PFA',$sstr_pre . '_' . $value1 . '_' . $value2);
                            if( $socre && ($socre%10)){
                                //删除
                                $this->redis->zDelete($this->preKey.'PFA',$sstr_pre . '_' . $value1 . '_' . $value2);
                            } else {
                                $this->redis->zAdd($this->preKey.'PFA',time()*10,$sstr_pre . '_' . $value1 . '_' . $value2);
                            }
                        }
                    }
                    $ret = $this->redis->exec();
                }else{
                    $ret = TRUE;
                }
            }
        }
        return $ret ;
    }

    /**
     * 获取集合列表
     */
    public function getListHandle($pre, $par, $page, $size,$order = 'desc') {
        $pre = $this->preKey.$pre;
        foreach ($par as $key => $value) {
            break;
        }
        if(!$value){
            return array();
        }
        $cacheKey = $pre . '_' . $key . '_' . $value;
        Log::info('getListHandle 缓存key:'.$cacheKey);
        if($order == 'asc' || $order == 'ASC' ){
            $ret = $this->redis->zRange($cacheKey, $page * $size, $page * $size + $size - 1, true);
        }else{
            $ret = $this->redis->zrevrange($cacheKey, $page * $size, $page * $size + $size - 1, true);
        }

        if (!$ret) {
            $ret = array();
        }
        return $ret;
    }

    /**
     * 获取总数
     */
    public function getTotalHandle($pre, $par) {
        $pre = $this->preKey.$pre;
        foreach ($par as $key => $value) {
            break;
        }
        if(!$value){
            return 0;
        }
        $cacheKey = $pre . '_' . $key . '_' . $value;
//        Log::info('getTotalHandle 缓存key:'.$cacheKey);
        $ret = $this->redis->zSize($cacheKey);
        if (!is_numeric($ret)) {
            $ret = 0;
        }
        return $ret;
    }

    /**
     * 获取关系
     */
    public function IsRelation($pre, $par1, $pra2, $par3 = '') {
        $pre = $this->preKey.$pre;
        foreach ($par1 as $key1 => $value1) {
            break;
        }
        $value = $pra2;
        if ($par3) {
            $value = $pra2 . '_' . $par3;
        }
        $cacheKey = $pre . '_' . $key1 . '_' . $value1;
        
        if(!$pra2 || !$value1){
            return FALSE;
        }
//        Log::info('IsRelation 缓存key:'.$cacheKey);
        $ret = $this->redis->zScore($cacheKey, $value);
        if (!$ret) {
            return FALSE;
        }
        return TRUE;
    }
    
    /**
     * 存实体
     */
    public function handleEty($action,$tkey,$object){
        if(!$tkey){
            return ;
        }
        $pre = $this->preKey.$tkey;
        $this->redis = $this->redis->multi();
        if($action == 'add' || $action == 'update' ){
            foreach ($object as $key => $value) {
                $this->redis = $this->redis->hSet($pre, $key, $value);
            }
        }else if($action == 'delete' ){
            $this->redis->delete($pre);
        }
        $ret = $this->redis->exec();
        return $ret;
    }
    
    /**
     * 获取实体
     * $key 实体key
     * $field 字段名 默认空则返回实体
     */
    public function getEty($key,$field = null) {
        if(!$key){
            return ;
        }
        $key = $this->preKey.$key;
        if($field){
            return $this->redis->hGet($key,$field); 
        }
        return $this->redis->hGetAll($key); 
    }
    
    /**
     * 同步redis至DB
     */
    public function syncFromRedisToDB() {
        $list = $this->redis->zRange($this->preKey.'PFA', 0, -1, true);
        foreach ($list as $key => $value) {
            $key_arr=explode('_',$key);
            $val_a = $value%10;
            $val_b = ($value-$val_a)/10;
            $flag = FALSE;
            if(count($key_arr) == 3){
                switch ($key_arr[0]){
                    case 'UAX'://关注人
                        $follower = Followers::where('user_id','=',$key_arr[1])
                            ->where('follow_id','=',$key_arr[2])
                            ->first();
                        if($val_a){ //添加
                            if($follower){
                                $follower->is_delete = 0;
                                $follower->time = $val_b;
                                $flag = $follower->save();
                            }else{
                                $follower = new Followers();
                                $follower->user_id = $key_arr[1];
                                $follower->follow_id = $key_arr[2];
                                $follower->time = $val_b;
                                $follower->is_delete = 0;
                                $flag = $follower->save();
                            }
                        }else{ //取消
                            if($follower){
                                $follower->is_delete = 1;
                                $follower->time = $val_b;
                                $flag = $follower->save();
                            }else{
                                $flag = TRUE;
                            }
                        }
                        break;
                    case 'UAT'://关注话题
                        $attention = Attention::where('user_id','=',$key_arr[1])
                            ->where('item_id','=',$key_arr[2])
                            ->where('type','=',1)
                            ->first();
                        if($val_a){ //添加
                            if($attention){
                                $attention->is_delete = 0;
                                $attention->time = $val_b;
                                $flag = $attention->save();
                            }else{
                                $attention = new Attention();
                                $attention->user_id = $key_arr[1];
                                $attention->item_id = $key_arr[2];
                                $attention->type = 1;
                                $attention->time = $val_b;
                                $attention->is_delete = 0;
                                $flag = $attention->save();
                            }
                        }else{ //取消
                            if($attention){
                                $attention->is_delete = 1;
                                $attention->time = $val_b;
                                $flag = $attention->save();
                            }else{
                                $flag = TRUE;
                            }
                        }
                        break;
                    case 'UAV'://关注节目
                        $attention = Attention::where('user_id','=',$key_arr[1])
                            ->where('item_id','=',$key_arr[2])
                            ->where('type','=',2)
                            ->first();
                        if($val_a){ //添加
                            if($attention){
                                $attention->is_delete = 0;
                                $attention->time = $val_b;
                                $flag = $attention->save();
                            }else{
                                $attention = new Attention();
                                $attention->user_id = $key_arr[1];
                                $attention->item_id = $key_arr[2];
                                $attention->type = 2;
                                $attention->time = $val_b;
                                $attention->is_delete = 0;
                                $flag = $attention->save();
                            }
                        }else{ //取消
                            if($attention){
                                $attention->is_delete = 1;
                                $attention->time = $val_b;
                                $flag = $attention->save();
                            }else{
                                $flag = TRUE;
                            }
                        }
                        break;
                    case 'UFC'://收藏内容
                        $favorite = Favorite::where('user_id','=',$key_arr[1])
                            ->where('content_id','=',$key_arr[2])
                            ->first();
                        if($val_a){ //添加
                            if($favorite){
                                $favorite->is_delete = 0;
                                $favorite->time = $val_b;
                                $flag = $favorite->save();
                            }else{
                                $favorite = new Favorite();
                                $favorite->user_id = $key_arr[1];
                                $favorite->content_id = $key_arr[2];
                                $favorite->time = $val_b;
                                $favorite->is_delete = 0;
                                $flag = $favorite->save();
                            }
                        }else{ //取消
                            if($favorite){
                                $favorite->is_delete = 1;
                                $favorite->time = $val_b;
                                $flag = $favorite->save();
                            }else{
                                $flag = TRUE;
                            }
                        }
                        break;
                    case 'UPC'://点赞内容
                        $praise = Praise::where('user_id','=',$key_arr[1])
                            ->where('item_id','=',$key_arr[2])
                            ->where('type','=',1)
                            ->first();
                        if($val_a){ //添加
                            if($praise){
                                $praise->is_delete = 0;
                                $praise->time = $val_b;
                                $flag = $praise->save();
                            }else{
                                $praise = new Favorite();
                                $praise->user_id = $key_arr[1];
                                $praise->item_id = $key_arr[2];
                                $praise->time = $val_b;
                                $praise->type = 1;
                                $praise->is_delete = 0;
                                $flag = $praise->save();
                            }
                        }else{ //取消
                            if($favorite){
                                $favorite->is_delete = 1;
                                $favorite->time = $val_b;
                                $flag = $favorite->save();
                            }else{
                                $flag = TRUE;
                            }
                        }
                        break;
                    case 'UPW'://点赞评论
                        $praise = Praise::where('user_id','=',$key_arr[1])
                            ->where('item_id','=',$key_arr[2])
                            ->where('type','=',2)
                            ->first();
                        if($val_a){ //添加
                            if($praise){
                                $praise->is_delete = 0;
                                $praise->time = $val_b;
                                $flag = $praise->save();
                            }else{
                                $praise = new Favorite();
                                $praise->user_id = $key_arr[1];
                                $praise->item_id = $key_arr[2];
                                $praise->time = $val_b;
                                $praise->type = 2;
                                $praise->is_delete = 0;
                                $flag = $praise->save();
                            }
                        }else{ //取消
                            if($favorite){
                                $favorite->is_delete = 1;
                                $favorite->time = $val_b;
                                $flag = $favorite->save();
                            }else{
                                $flag = TRUE;
                            }
                        }
                        break;
                }
            }
            if($flag){
                //删除
                $this->redis->zDelete($this->preKey.'PFA',$key);
            }
        }
    }
    
}
